/* eslint-disable */
const User = require("../model/user/user")
const { need_token } = require("./needToken")
const {
    checkAll
} = require("./findModel")

const check = (rule) => {
    try {
        return async function (ctx, next) {
            let token = await need_token(ctx.headers.authorization)
            // 将编辑者和添加者设置为解析完之后的token字段中的 "username" 值
            // switch(ctx.request.method){
            //     case "POST" : ctx.request.body.creator = token.username; break;
            //     case "PUT" : ctx.request.body.updator = token.username; break;
            // }
            // 将前端传过来的pageNum和pageSize转换成Number类型 方便后期获取分页操作
            ctx.query.pageNum = Number(ctx.query.pageNum)
            ctx.query.pageSize = Number(ctx.query.pageSize)
            if (token.username === "admin") {
                await next()
            } else {
                if (token.code == 200) {
                    let res = await checkAll(rule, token.username)
                    if (res.code === "200") {
                        await next()
                    } else {
                        // 如果用户编辑自己的资料 则通过
                        if (rule == "edituser") {
                            const { id } = ctx.params
                            let name = await User.findOne({ attributes: ["username"], where: { id } })
                            if (token.username == name.username) {
                                await next()
                            } else {
                                ctx.body = {
                                    msg: "操作失败 您没有编辑其他用户的权限",
                                    code: "400",
                                }
                            }
                        } else {
                            ctx.body = {
                                msg: res.msg,
                                code: "400",
                            }
                        }
                    }
                } else {
                    ctx.body = {
                        msg: "token验证失败1",
                        code: "400"
                    }
                }
            }

        }
    } catch (err) {
        ctx.body = {
            msg: "操作失败",
            code: "400",
            error: err
        }
    }
}


module.exports = { check }